package com.css.common.core.utils.yl;

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.css.common.core.utils.GyUtils;
import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;

public class YlswUtils {
	public final static String YLSWTOKEN_KEY="ylswAccessToken";//成功返回的code
	public final static String YLSWOCRTOKEN_KEY="ylswOCRAccessToken";//成功返回的code
	public final static String YHK_TOKEN_SUCCESS_CODE="0000";//成功返回的code
	public final static String YHK_SUCCESS_CODE="20000000";//成功返回的code
	public final static String OCR_SUCCESS_CODE="AN000000";//成功返回的code
	private final static DateTimeFormatter dateTimeFormatter =  DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
	//取报文体，即正文全部内容获得字节数组A，进行SHA256算法取16进制小写字符串获得B
    //取AppId，Timestamp，Nonce，B进行字符串拼接，以UTF-8进行编码获得待签名串C，取AppKey作为签名密钥D
    //以C和D进行HMAC-SHA256算法获得签名字节数组E
    //对E进行Base64编码获得F，F即为签名内容
    public static String getOpenBodySig(String appId, String appKey, byte[] body) throws Exception {
    	final String timestamp = LocalDateTime.now().format(dateTimeFormatter);
        final String nonce = IdUtil.fastSimpleUUID(); 
        String bodyDigest = DigestUtils.sha256Hex(body);
        String str1_C = appId + timestamp + nonce + bodyDigest;
        byte[] localSignature = hmacSHA256(str1_C.getBytes(), appKey.getBytes());
        String localSignatureStr = org.apache.commons.codec.binary.Base64.encodeBase64String(localSignature);
        return ("OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"");
    }
    

    private static byte[] hmacSHA256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data);
    }
    //signature=SHA256_hex(appId+timestamp+nonce+appKey)sha256加密,返回64位十六进制字符串
    public static String getSignature(String appId,String timestamp,String nonce,String appKey) { 
        final String decript = appId + timestamp + nonce + appKey;
        System.out.println("22222="+DigestUtil.sha256Hex(appId+timestamp+nonce+appKey));
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			 System.out.println("3333333="+hexString.toString());
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "ERROR";
		}
	
    }
    
    public static Map<String,Object> getOCRFieldData(JSONObject data) {
		final Map<String,Object> map = new HashMap<String, Object>();
		if (GyUtils.isNull(data)) {
			return map;
		}
		final String pageInfo = data.getString("PageInfo");
		if (GyUtils.isNotNull(pageInfo)) {
			final String result = JSONObject.parseArray(pageInfo).getJSONObject(0).getString("Result");
			if (GyUtils.isNotNull(result)) {
				final String resultList = JSONObject.parseArray(result).getJSONObject(0).getString("ResultList");
				if (GyUtils.isNotNull(resultList)) {
					final String fieldList = JSONObject.parseArray(resultList).getJSONObject(0).getString("FieldList");
					if (GyUtils.isNotNull(fieldList)) {
						final JSONArray jSONArray = JSONObject.parseArray(fieldList);
						for (Object obj:jSONArray) {
							final JSONObject json = JSONObject.parseObject(obj.toString());
							final String key = json.getString("key");
							final String value = json.getString("value");
							map.put(key, value);
						}
					}    					
				}
			}
		}
		return map;		
    }
}